<!--
 * @Author: xiaotiwen
 * @Date: 2020-05-15 16:08:28
 * @LastEditTime: 2020-07-13 15:24:43
 * @LastEditors: xiaotiwen
 * @FilePath: \eduweb\src\views\practiceManagement\dispersionPracticeApply\practiceApply.vue
 * @Description: 分散实习申请组件
 -->
<template>
    <div class="practiceApply">
        <wordTable :data="data" :label="label" />
        <div class="practiceApply_form">
            <el-form ref="form" :model="form" :rules="rules" label-width="150px">
                <el-row>
                    <el-col :span="12">
                    <el-form-item v-if="showStuFlag" :label="$t('practiceReworkManagement.label.applyForStudent')" prop="stuInfo" >
                    <!-- multiple -->
                    <el-select :disabled="!chooseFlag"
                        v-model="form.stuInfo"
                        :remote-method="selectStu"
                        @change="changeStu($event)"
                        value-key="studentId"
                        :placeholder="$t('common.pla.pleaseSelect')"
                        filterable
                        remote
                        :clearable="true"
                        v-clearreadonly
                    >
                        <el-option
                            v-for="item in students"
                            :key="item.studentId"
                            :label="item.label"
                            :value="item.value"
                        />
                        </el-select>
                    </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('dispersionPracticeApply.label.subCourseNo')"
                            prop="obj"
                        >
                            <el-select
                                v-model="form.obj"
                                style="width:100%;"
                                value-key="subCourseNo"
                                @change="change"
                            >
                                <el-option
                                    v-for="item in options"
                                    :key="item.subCourseNo"
                                    :label="item.courseName"
                                    :value="item"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('dispersionPracticeApply.label.practiceDateStart')"
                            prop="practiceDateStart"
                        >
                            <el-date-picker
                                v-model="form.practiceDateStart"
                                format="yyyy-MM-dd"
                                value-format="timestamp"
                                type="date"
                                :placeholder="$t('message.plzSelect')"
                                :picker-options="pickerOptions1"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('dispersionPracticeApply.label.practiceDateEnd')"
                            prop="practiceDateEnd"
                        >
                            <el-date-picker
                                v-model="form.practiceDateEnd"
                                format="yyyy-MM-dd"
                                value-format="timestamp"
                                type="date"
                                :placeholder="$t('message.plzSelect')"
                                :picker-options="pickerOptions2"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('dispersionPracticeApply.label.practiceAddr')"
                            prop="practiceAddr"
                        >
                            <el-input
                                v-model="form.practiceAddr"
                                maxlength="100"
                                :placeholder="$t('fundingManagement.tips.plzInput')"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('dispersionPracticeApply.label.practiceEnterprise')"
                            prop="practiceEnterprise"
                        >
                            <el-input
                                v-model="form.practiceEnterprise"
                                maxlength="50"
                                :placeholder="$t('fundingManagement.tips.plzInput')"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('dispersionPracticeApply.label.enterpriseContactUser')"
                            prop="enterpriseContactUser"
                        >
                            <el-input
                                v-model="form.enterpriseContactUser"
                                maxlength="20"
                                :placeholder="$t('fundingManagement.tips.plzInput')"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('dispersionPracticeApply.label.position')"
                            prop="position"
                        >
                            <el-input
                                v-model="form.position"
                                maxlength="20"
                                :placeholder="$t('fundingManagement.tips.plzInput')"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item
                            :label="$t('dispersionPracticeApply.label.enterpriseContactPhone')"
                            prop="enterpriseContactPhone"
                        >
                            <el-input
                                v-model="form.enterpriseContactPhone"
                                :placeholder="$t('fundingManagement.tips.plzInput')"
                                maxlength="11"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item
                            :label="$t('dispersionPracticeApply.label.practicePlan')"
                            prop="practicePlan"
                        >
                            <el-input
                                v-model="form.practicePlan"
                                maxlength="200"
                                :rows="4"
                                type="textarea"
                                :placeholder="$t('fundingManagement.tips.plzInput')"
                                resize="none"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item :label="$t('dispersionPracticeApply.label.attachName')">
                            <el-upload
                                :headers="{ 'X-Token': $store.state.session.sessionid }"
                                :data="{ bucketname: 'face', folderpath: 'file' }"
                                :before-upload="beforeUpload"
                                :limit="1"
                                :on-exceed="handleExceed"
                                :on-remove="onRemove"
                                :file-list="fileList"
                                class="upload-demo"
                                action="/api/commonservice/obsfile/uploadfile"
                                :on-success="uploadDone"
                            >
                                <div class="practiceApply_upload">
                                    <el-button
                                        size="small"
                                        type="primary"
                                    >{{$t('dispersionPracticeApply.btn.clickUpload')}}</el-button>
                                    <div
                                        class="practiceApply_upload_div"
                                    >{{$t('dispersionPracticeApply.tips.fileLimit')}}</div>
                                </div>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
    </div>
</template>

<script>
import UTILS from 'common/src/utils/utils'
import wordTable from '../common/wordTable'
import { getDetail, getCourses } from 'common/src/api/practiceManagement/dispersionPracticeApply'
import { getStuInfoByParam, findStuInfoListForSelect } from 'common/src/api/studentinfo'
import { findCampusProfessionList } from 'common/src/api/culture/campusProfession'
import commonMixins from 'common/src/views/practiceManagement/commonMixins'
import mixin from 'common/src/mixins/index';
export default {
    // 组件名称
    name: 'PracticeApply',
    mixins: [commonMixins,mixin],
    // 局部注册的组件
    components: {
        wordTable
    },
    // 组件参数 接收来自父组件的数据
    props: {
        ids: {
            type: String,
            default: ''
        },
        yearTerm: {
            type: String,
            default: ''
        },
        chooseFlag:{
            type: Boolean,
            default: false
        },
        showStuFlag:{
            type: Boolean,
            default: false
        }
    },
    // 组件状态值
    data() {
        return {
            form: {
                obj: {
                    // 已选课程
                    courseName: '',
                    subCourseNo: '',
                    courseOpenAcademyId:'',
                    courseOpenAcademy:''
                },

                practiceDateStart: '', // 实习开始时间
                practiceDateEnd: '', // 实习结束时间
                practiceAddr: '', // 实习地点
                practiceEnterprise: '', // 实习单位
                enterpriseContactUser: '', // 实习联系人
                position: '', // 职位
                enterpriseContactPhone: '', // 联系电话：
                practicePlan: '', // 实习计划
                udgPtAttachTs: [], // 证明材料
                stuInfo: null
            },
            data: {}, // 数据类型
            fileList: [],
            options: [],
            label: [
                [
                    { label: this.$t('label.stuCode'), props: 'studentNo' },
                    { label: this.$t('label.stuName'), props: 'studentName' }
                ],
                [
                    { label: this.$t('label.college'), props: 'acdemyName' },
                    { label: this.$t('label.major'), props: 'majorName' }
                ],
                [{ label: this.$t('label.grade'), props: 'grade' }]
            ],
            rules: {
                practiceDateStart: [
                    {
                        required: true,
                        message: this.$t('fundingManagement.tips.plzInput'),
                        trigger: ['blur']
                    }
                ],
                practiceDateEnd: [
                    {
                        required: true,
                        message: this.$t('fundingManagement.tips.plzInput'),
                        trigger: ['blur']
                    }
                ],
                practiceAddr: [
                    {
                        required: true,
                        message: this.$t('fundingManagement.tips.plzInput'),
                        trigger: ['blur']
                    },
                    {
                        required: true,
                        validator: this.validateInput,
                        trigger: 'blur'
                    }
                ],
                practiceEnterprise: [
                    {
                        required: true,
                        message: this.$t('fundingManagement.tips.plzInput'),
                        trigger: ['blur']
                    },
                    {
                        required: true,
                        validator: this.validateInput,
                        trigger: 'blur'
                    }
                ],
                enterpriseContactUser: [
                    {
                        required: true,
                        message: this.$t('fundingManagement.tips.plzInput'),
                        trigger: ['blur']
                    },
                    {
                        required: true,
                        validator: this.validateInput,
                        trigger: 'blur'
                    }
                ],
                position: [
                    {
                        validator: this.validateRemark,
                        trigger: 'blur'
                    }
                ],
                enterpriseContactPhone: [
                    {
                        required: true,
                        message: this.$t('fundingManagement.tips.plzInput'),
                        trigger: ['blur']
                    },
                    {
                        pattern: /^1(3|4|5|6|7|8|9)\d{9}$/,
                        message: this.$t('dispersionPracticeApply.tips.phoneNumber'),
                        trigger: ['blur']
                    }
                ],
                practicePlan: [
                    {
                        required: true,
                        message: this.$t('fundingManagement.tips.plzInput'),
                        trigger: ['blur']
                    },
                    {
                        required: true,
                        validator: this.validateInput,
                        trigger: 'blur'
                    }
                ],
                obj: [
                    {
                        required: true,
                        validator: this.validateSurnmae,
                        trigger: 'blur'
                    }
                ],
                stuInfo: [
                    {
                        required: true,
                        message: this.$t('practiceReworkManagement.tips.mustWrite'),
                        trigger: ['change']
                    }
                ]
            },
            pickerOptions1: {
                disabledDate: time => {
                    if (this.form.practiceDateEnd) {
                        return time.getTime() > new Date(this.form.practiceDateEnd).getTime()
                    }
                }
            },
            pickerOptions2: {
                disabledDate: time => {
                    if (this.form.practiceDateStart) {
                        return time.getTime() < new Date(this.form.practiceDateStart).getTime()
                    }
                }
            },
            stuInfo:null,
            students:[]
        }
    },
    // 计算属性
    computed: {},
    // 侦听器
    watch: {},
    /**
     * 在实例初始化之后，组件属性计算之前，如data属性等
     */
    created() {},
    /**
     * 在挂载开始之前被调用：相关的 render 函数首次被调用。
     */
    mounted() {
        this.getDetails()
    },
    // 组件方法
    methods: {
        validateSurnmae(rule, value, callback) {
            if (!this.form.obj.courseName) {
                return callback(new Error(this.$t('fundingManagement.tips.plzInput')))
            } else {
                return callback()
            }
        },
        save(type) {
            let data = null
            let jsons = {
                studentNo: this.data.studentNo,
                studentName: this.data.studentName,
                acdemyName: this.data.acdemyName,
                grade: this.data.grade,
                majorName: this.data.majorName,
                acdemyId: this.data.acdemyId,
                majorId: this.data.majorId,
                courseName: this.form.obj.courseName,
                subCourseNo: this.form.obj.subCourseNo,
                courseOpenAcademyId: this.form.obj.courseOpenAcademyId,
                courseOpenAcademy:this.form.obj.courseOpenAcademy
            }
            if (type === 'save') {
                // 保存
                let jsonData = Object.assign(jsons, this.form)
                data = jsonData
                if (this.form.practiceAddr) {
                    this.$refs.form.validateField('practiceAddr', valid => {
                        if (valid) {
                            data = false
                        }
                    })
                }
                if (this.form.practiceEnterprise) {
                    this.$refs.form.validateField('practiceEnterprise', valid => {
                        if (valid) {
                            data = false
                        }
                    })
                }
                if (this.form.enterpriseContactUser) {
                    this.$refs.form.validateField('enterpriseContactUser', valid => {
                        if (valid) {
                            data = false
                        }
                    })
                }
                if (this.form.position) {
                    this.$refs.form.validateField('position', valid => {
                        if (valid) {
                            data = false
                        }
                    })
                }
                if (this.form.practicePlan) {
                    this.$refs.form.validateField('practicePlan', valid => {
                        if (valid) {
                            data = false
                        }
                    })
                }
                if (this.form.enterpriseContactPhone) {
                    this.$refs.form.validateField('enterpriseContactPhone', valid => {
                        if (valid === this.$t('dispersionPracticeApply.tips.phoneNumber')) {
                            data = false
                        }
                    })
                }
            } else if (type === 'submit') {
                // 提交
                this.$refs.form.validate(valid => {
                    if (valid) {
                        let jsonData = Object.assign(jsons, this.form)
                        data = jsonData
                    } else {
                        data = false
                    }
                })
            }
            return data
        },
        getDetails() {
            // 获取详情
            if (this.ids) {
                getDetail({ id: this.ids }).then(res => {
                    this.data = res.data
                    this.form = this.data
                    if (this.form.practiceDateStart) {
                        this.form.practiceDateStart = new Date(this.form.practiceDateStart)
                    }
                    if (this.form.practiceDateEnd) {
                        this.form.practiceDateEnd = new Date(this.form.practiceDateEnd)
                    }
                    if (this.data.udgPtAttachTs.length >= 1) {
                        this.fileList = [
                            {
                                name: this.data.udgPtAttachTs[0].attachName,
                                url: this.data.udgPtAttachTs[0].attachPath
                            }
                        ]
                    }
                    this.form.obj = {
                        courseName: this.form.courseName,
                        subCourseNo: this.form.subCourseNo,
                        courseOpenAcademyId: this.form.courseOpenAcademyId,
                        courseOpenAcademy: this.form.courseOpenAcademy
                    }
                    this.getCourses()
                })
            } else if(!this.showStuFlag){
                this.data = this.global.currentUser
                this.$set(this.data, 'acdemyId', this.data.faculty)
                this.$set(this.data, 'studentNo', this.data.uid)
                this.$set(this.data, 'studentName', this.data.name)
                this.$set(this.data, 'acdemyName', this.data.facultyName)
                // 获取当前学生的年级专业
                getStuInfoByParam(this.data.uid, encodeURIComponent('学籍信息')).then(res => {
                    // 获取年级
                    let grade
                    let major
                    res.data.forEach(function(value, i) {
                        if (value.columnStr === 'CULTURE_PROFESSION_') {
                            major = value.value
                        }
                        if (value.columnStr === 'CURRENT_GRADE_') {
                            grade = value.value
                            //年级排序在专业之后，判断年级获取到即可
                            return
                        }
                    })
                    this.data.grade = grade
                    // 通过年级专业code获取专业的名称
                    this.query(major, this.data.grade)
                    this.getCourses()
                })
            }
        },
        handleExceed(files, fileList) {
            // 文件超出个数限制时的钩子
            this.$message.warning(
                UTILS.i18nReplace(this.$t('dispersionPracticeApply.tips.fileTips'), {
                    first: files.length,
                    second: files.length + fileList.length,
                    third: 1
                })
            )
        },
        beforeUpload(file) {
            return UTILS.checkFile(
                file,
                {
                    name: '.jpg,.png,.gif,.doc,.docx,.xls,.xlsx,.pdf',
                    size: '10'
                },
                this
            )
        },
        uploadDone(res, file) {
            let jsons = {
                attachName: file.name,
                attachSize: file.size,
                attachPath: Object.values(file.response.data)[0].objectkey
            }
            this.form.udgPtAttachTs = [jsons]
        },
        onRemove(file, fileList){
            this.form.udgPtAttachTs = []
        },
        query(profession, grade) {
            // 专业代号查专业
            let lang = this.$store.getters.language || 'cn'
            let param = {}
            param.grade = grade
            param.keyWord = profession
            param.pageSize_ = 1
            param.pageNum_ = 1
            findCampusProfessionList(param).then(res => {
                let data = res.data.list
                if (data && data.length > 0) {
                    this.$set(this.data, 'majorId', data[0].professionCode)
                    this.$set(this.data, 'acdemyId', data[0].faculty)
                    if (lang === 'cn') {
                        this.$set(this.data, 'majorName', data[0].professionName)
                    } else {
                        this.$set(this.data, 'majorName', data[0].professionNameEn)
                    }
                }
            })
        },
        timeChange() {
            // 时间校验
            let time1 = this.form.practiceDateStart
            let time2 = this.form.practiceDateEnd
            if (time1 && time2) {
                if (new Date(time1).getTime() > new Date(time2).getTime()) {
                    this.$message({
                        type: 'warning',
                        message: this.$t('dispersionPracticeApply.tips.timeCheck')
                    })
                    return true
                }
            }
        },
        getCourses() {
            // 已选课程
            let jsonData = {
                studentNo: this.data.studentNo,
                yearTerm: this.yearTerm,
                subCourseNo: this.form.obj.subCourseNo,
                courseName:this.form.obj.courseName,
                courseOpenAcademy: this.form.obj.courseOpenAcademy || '',
                courseOpenAcademyId: this.form.obj.courseOpenAcademyId || ''
            }
            getCourses(jsonData).then(res => {
                if (res.data && res.data.length > 0) {
                    this.options = res.data
                }
            })
        },
        change() {
            this.$refs.form.validateField('obj', valid => {
                if (valid) {
                    data = false
                }
            })
            this.$forceUpdate()
        },
        changeStu(item){
            if (!item || !item.studentId) return;
            if(item){
                this.$set(this.data, 'studentNo', item.studentId);
                this.$set(this.data, 'studentName', item.name);
                this.$set(this.data, 'acdemyName', item.facultyI18n);
                this.$set(this.data, 'acdemyId', item.faculty)
                this.$set(this.data, 'majorId', item.cultureProfession)
                this.$set(this.data, 'grade', item.grade)
                this.$set(this.data, 'majorName', item.cultureProfessionI18n)
            }
            let jsonData = {
                studentNo: item.studentId,
                yearTerm: this.yearTerm
            }
            getCourses(jsonData).then(res1 => {
                if (res1 && res1.code !== 200) {
                    this.$message({ message: res.msg, type: 'warning' })
                    return
                }
                if(res1.data.length>0){
                    this.options = res1.data
                }
            })
        },
        transStudentData(list, name, code) {
            return list.map((item, index, array) => {
                return {
                    label: item[name] + '(' + item[code] + ')',
                    value: item,
                }
             })
        },
        // 查询学生信息接口
        selectStu (query) {
            if (!query) return;
            const data = {
                name: query,
                pageNum_: 1,
                pageSize_: 50
            }
            this.loading = true
            findStuInfoListForSelect(data).then(res => {
                this.loading = false
                if (res.code == 200) {
                    this.students = this.transStudentData(res.data.list, 'name', 'studentId')
                    // this.students = res.data.list
                } else throw res.code
            })
            .catch(error => {
              this.loading = false
              this.$message({
                  type: 'error',
                  message: '查询用户出错'
              })
            })
        }
    }
}
</script>
<style lang="scss" scoped>
.practiceApply {
    &_form {
        padding-top: 20px;
    }
    &_upload {
        display: flex;
        align-items: center;
        &_div {
            margin-left: 10px;
        }
    }
    &_files {
        color: blue;
        cursor: pointer;
        display: flex;
        flex-direction: column;
    }
    ::v-deep .el-upload-list__item {
        width: 220px;
    }
    ::v-deep .el-form-item__content {
        display: flex;
    }
    ::v-deep .el-date-editor--date {
        flex: auto;
    }
}
</style>
